package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.ProFile;
import com.ruoyi.system.domain.bo.ProTaskBo;
import com.ruoyi.system.domain.vo.ProTaskVo;
import com.ruoyi.system.service.IProFileService;
import com.ruoyi.system.service.IProTaskService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.ProProcessBo;
import com.ruoyi.system.domain.vo.ProProcessVo;
import com.ruoyi.system.domain.ProProcess;
import com.ruoyi.system.mapper.ProProcessMapper;
import com.ruoyi.system.service.IProProcessService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 执行记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-07
 */
@RequiredArgsConstructor
@Service
public class ProProcessServiceImpl implements IProProcessService {

    private final ProProcessMapper baseMapper;

    private final IProTaskService proTaskService;

    private final ISysUserService sysUserService;

    private final IProFileService proFileService;

    private final String FILE_KEY = "PROCESS";

    /**
     * 查询执行记录
     */
    @Override
    public ProProcessVo queryById(Long processId){
        ProProcessVo proProcessVo = baseMapper.selectVoById(processId);
        List<ProFile> proFiles = proFileService.queryListByKeyAndRefId(FILE_KEY, proProcessVo.getProcessId());
        proProcessVo.setFileList(proFiles);
        return proProcessVo;
    }

    /**
     * 查询执行记录列表
     */
    @Override
    public TableDataInfo<ProProcessVo> queryPageList(ProProcessBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ProProcess> lqw = buildQueryWrapper(bo);
        lqw.orderBy(true,false,ProProcess::getCreateTime);
        Page<ProProcessVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        for (ProProcessVo record : result.getRecords()) {
            List<ProFile> proFiles = proFileService.queryListByKeyAndRefId(FILE_KEY, record.getProcessId());
            record.setFileList(proFiles);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询执行记录列表
     */
    @Override
    public List<ProProcessVo> queryList(ProProcessBo bo) {
        LambdaQueryWrapper<ProProcess> lqw = buildQueryWrapper(bo);
        List<ProProcessVo> proProcessVos = baseMapper.selectVoList(lqw);
        proProcessVos.forEach(item->{
            SysUser sysUser = sysUserService.selectUserByUserName(item.getCreateBy());
            if(ObjectUtils.isNotNull(sysUser)){
                item.setCreateName(sysUser.getNickName());
            }
            List<ProFile> proFiles = proFileService.queryListByKeyAndRefId(FILE_KEY, item.getProcessId());
            item.setFileList(proFiles);
        });
        return proProcessVos;
    }

    private LambdaQueryWrapper<ProProcess> buildQueryWrapper(ProProcessBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ProProcess> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTaskId() != null, ProProcess::getTaskId, bo.getTaskId());
        lqw.eq(bo.getSubjectId() != null, ProProcess::getSubjectId, bo.getSubjectId());
        lqw.eq(StringUtils.isNotBlank(bo.getSubjectNo()), ProProcess::getSubjectNo, bo.getSubjectNo());
        lqw.eq(StringUtils.isNotBlank(bo.getDesp()), ProProcess::getDesp, bo.getDesp());
        lqw.eq(bo.getBeginDate() != null, ProProcess::getBeginDate, bo.getBeginDate());
        lqw.eq(bo.getPfinishDate() != null, ProProcess::getPfinishDate, bo.getPfinishDate());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ProProcess::getStatus, bo.getStatus());
        lqw.eq(bo.getRate() != null, ProProcess::getRate, bo.getRate());
        return lqw;
    }

    /**
     * 新增执行记录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ProProcessBo bo) {
        ProProcess add = BeanUtil.toBean(bo, ProProcess.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setProcessId(add.getProcessId());
        }
        ProTaskVo proTaskVo = proTaskService.queryById(add.getTaskId());
        if(ObjectUtils.isNull(proTaskVo)){
            throw new ServiceException("任务不存在"+add.getTaskId());
        }
        ProTaskBo proTaskBo = BeanUtil.toBean(proTaskVo, ProTaskBo.class);
        proTaskBo.setRate(add.getRate());
        if(ObjectUtils.isNotEmpty(bo.getFileList())){
            for (ProFile file : bo.getFileList()) {
                file.setVkey(FILE_KEY);
                file.setRefId(add.getProcessId());
                proFileService.insertByBo(file);
            }
        }
        proTaskService.updateByBo(proTaskBo);
        return flag;
    }

    /**
     * 修改执行记录
     */
    @Override
    public Boolean updateByBo(ProProcessBo bo) {
        ProProcess update = BeanUtil.toBean(bo, ProProcess.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ProProcess entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除执行记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


}
